package database

import (
	"dmgorm2"
	"fmt"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
	"tupu-go/config"
	"tupu-go/model"
)

var DB *gorm.DB

func InitDB(cfg config.DMDatabaseConfig) error {
	dialector := dm.New(dm.Config{
		DSN: cfg.DSN,
	})

	// 配置GORM日志级别，启用SQL语句打印
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // 日志输出目的地
		logger.Config{
			SlowThreshold:             time.Second, // 慢查询阈值
			LogLevel:                  logger.Info, // 日志级别：Info会打印所有SQL语句
			IgnoreRecordNotFoundError: true,        // 忽略记录未找到错误
			ParameterizedQueries:      false,       // 不参数化查询，显示完整SQL
			Colorful:                  true,        // 启用彩色日志
		},
	)

	db, err := gorm.Open(dialector, &gorm.Config{
		Logger: newLogger, // 设置自定义日志
	})
	if err != nil {
		fmt.Printf("数据库连接失败: %v\n", err)
		return err
	}
	fmt.Println("数据库连接成功")
	DB = db

	//err = Migrate()
	//if err != nil {
	//	fmt.Printf("数据库表迁移失败: %v\n", err)
	//	return err
	//}
	fmt.Println("数据库表迁移成功")
	return nil
}

func GetDB() *gorm.DB {
	return DB
}

func Migrate() error {
	db := GetDB()
	return db.Transaction(func(tx *gorm.DB) error {
		tables := []interface{}{
			&model.NodeType{},
			&model.EdgeType{},
			&model.NodeAttribute{},
			&model.EdgeAttribute{},
			&model.RelationModel{},
			&model.RelationModelNodeType{},
			&model.RelationModelEdgeType{},
			&model.Task{},
			&model.ImportRecord{},
			&model.TEmployeeOrganizationRel{},
			&model.TEmployee{},
			&model.Permission{},
			&model.KeyPermission{},
			&model.OrganizationStruct{},
		}

		for _, table := range tables {
			if err := tx.
				Set("gorm:table_name_quote", false). // 禁用表名引号
				AutoMigrate(table); err != nil {
				return fmt.Errorf("迁移表 %T 失败: %w", table, err)
			}
		}

		return nil
	})
}
